package api

import (
	"blog/models"
	"github.com/astaxie/beego"
	"github.com/astaxie/beego/validation"
)

type LoginController struct {
	beego.Controller
}

func (c *LoginController) Login() {

	Account := c.GetString("account")
	Password := c.GetString("password")

	valid := validation.Validation{}
	valid.Required(Account, "account")
	valid.Required(Password, "password")

	if valid.HasErrors() {
		for _, err := range valid.Errors {
			c.Data["json"] = map[string]interface{}{"code": 2, "message": err.Key + "" + err.Message}
		}
	}

	err, _ := models.LoginUser(Account, Password)

	if err == nil {

		c.SetSession("AdminLogin", 1)
		c.Data["json"] = map[string]interface{}{"code": 0, "message": "登录成功"}

	} else {

		c.Data["json"] = map[string]interface{}{"code": 1, "message": "账号或密码错误"}
	}

	c.ServeJSON()
}

func (c *LoginController) Logout() {

	c.DelSession("AdminLogin")

	c.Data["json"] = map[string]interface{}{"code": 0, "message": "退出登录成功"}

	c.ServeJSON()
}
